package com.vgemv.jsutilitysdk.Display.JsActivityContentDisplayManager;

import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Looper;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;

import com.vgemv.jsutilitysdk.Display.JsViewDisplayManager.JsViewDisplayManager;
import com.vgemv.jsutilitysdk.Display.JsViewDisplayManager.JsViewDisplayStyle;
import com.vgemv.jsutilitysdk.Display.JsViewDisplayManager.JsViewUndisplayCallback;
import com.vgemv.jsutilitysdk.geometry.JsGeometryManager;
import com.vgemv.jsutilitysdk.Reminder.JsLoadingReminderStandard1;
import com.vgemv.jsutilitysdk.Reminder.JsReminderManager;
import com.vgemv.jsutilitysdk.JsThread.JsThreadManager;
import com.vgemv.jsutilitysdk.log.JsLogManager;

import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

//TODO: window需要让子view可以点击,但是本身能穿透事件.

/**
 * 显示到Activity级别的window
 */

public class JsActivityContentDisplayManager {

    private static JsActivityContentDisplayManager _sharedInstance;

     public HashMap<View, FrameLayout> map_container = new HashMap<>();
     public  HashMap<View, ViewTreeObserver.OnGlobalLayoutListener> map_observer = new HashMap<>();
     public  HashMap<View, JsDisplayCallback> map_callback = new HashMap<>();
    //用来保存contentView和其显示的style
     public  HashMap<View, JsViewDisplayStyle> map_style = new HashMap<>();
    //用来保存contentView和取消的定时器timer.
     public  HashMap<View, Timer> map_timer = new HashMap<>();


    //Activity和关联的loading计数.
    public HashMap<Activity, Integer> mMap_loadingCount;
    //Activity和loadingReminder的关联.
    public HashMap<Activity, View> mMap_loadingReminder = new HashMap<>();


    //主线程的Handler
    private static final Handler mHandler_main = new Handler(Looper.getMainLooper());

    /**
     * 窗口参数
     */
    public WindowManager.LayoutParams mLayoutParams_display;

    JsActivityContentDisplayManager() {

    }

    public static JsActivityContentDisplayManager sharedInstance() {
        if(_sharedInstance == null) {
            _sharedInstance = new JsActivityContentDisplayManager();
        }
        return _sharedInstance;
    }


    //ActivityLoadingCount的操作.
    public int getActivityLoadingCount(Activity activity) {
        if(mMap_loadingCount == null) {
            return 0;
        }
        Integer loadingCount = mMap_loadingCount.get(activity);
        if(loadingCount == null) {
            return 0;
        }
        return loadingCount.intValue();
    }
    //activityLoadingCount + 1
    public int increaseActivityLoadingCount(Activity activity) {
        if(mMap_loadingCount == null) {
            mMap_loadingCount = new HashMap<>();
            mMap_loadingCount.put(activity,1);
            return 1;
        }
        Integer loadingCount = mMap_loadingCount.get(activity);
        if(loadingCount == null) {
            mMap_loadingCount.put(activity,1);
            return 1;
        }
        if(loadingCount.intValue() >=0) {
            mMap_loadingCount.put(activity,loadingCount+1);
            return loadingCount+1;
        }
        else {
            mMap_loadingCount.put(activity,1);
            return 1;
        }
    }
    //activityLoadingCount - 1
    public int decreaseActivityLoadingCount(Activity activity) {
        if(mMap_loadingCount == null) {
            return 0;
        }
        Integer loadingCount = mMap_loadingCount.get(activity);
        if(loadingCount == null) {
            //返回0 移除该activity.
            mMap_loadingCount.remove(activity);
            return 0;
        }
        if(loadingCount.intValue() >=2) {
            mMap_loadingCount.put(activity,loadingCount-1);
            return loadingCount-1;
        }
        else {
            //返回0 移除该activity.
            mMap_loadingCount.remove(activity);
            return 0;
        }
    }


    //获取当前activity的loadingReminder,没有则创建新的,并存储.
    public View getLoadingReminder(Activity activity) {
        View loadingReminder = mMap_loadingReminder.get(activity);
        if(loadingReminder == null) {
            loadingReminder = JsReminderManager.getLoadingRemindStandard1(activity);
            mMap_loadingReminder.put(activity,loadingReminder);
        }
        return loadingReminder;
    }

    /**
     * 1-1 显示loading到activity上.
     * @param activity
     */
    public void displayLoadingReminder(Activity activity,JsDisplayStyle style) {
        //1 显示计数管理,并生成loadingRemingerView.
        int loadingCount = getActivityLoadingCount(activity);
        if (loadingCount == 0) {
            View loadingReminder = getLoadingReminder(activity);
            display(activity,loadingReminder,style,null);
        }
        increaseActivityLoadingCount(activity);
    }

    /**
     * 1-2 显示loading到activity上.
     * @param activity
     */
    public void displayLoadingReminder(Activity activity) {
        JsDisplayStyle style = new JsDisplayStyle();
        //默认用110dp.居中显示.
        int size = JsGeometryManager.pixelFromDp(110);
        RelativeLayout.LayoutParams contentViewInitialLayoutParams = new RelativeLayout.LayoutParams(size, size);
        contentViewInitialLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        style.mRelativeLayoutParams_contentViewInitialLayoutParams = contentViewInitialLayoutParams;
        style.isMaskViewClickable = false;

        displayLoadingReminder(activity,style);
    }

    /**
     * 生成maskView,每个contentView都要生成maskView.
     * 根据style的设置,确定maskView是否可见,是否点击undisplay.
     * @param context
     * @return
     */
    private RelativeLayout generateMaskView(Context context, JsDisplayStyle style) {
        final RelativeLayout maskView = new RelativeLayout(context);
        maskView.setId(View.generateViewId());
        if(style.mb_isMaskViewVisible) {
            //深色.
            maskView.setBackgroundColor(Color.argb(60, 60, 60, 60));
        }
        else {
            //透明色.
        }
        if(style.mb_isMaskViewClickCancel) {
            maskView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    View contentView = maskView.getChildAt(0);
                    undisplay(contentView);
                }
            });
        }
        return maskView;
    }

    /**
     * 显示view到activity的最核心代码.
     * @param activity
     * 要展示的activity的位置
     *
     * @param contentView
     * 要展示的内容.
     *
     * @param style
     * 展示的样式,包括位置,大小.
     *
     * @param callback
     *
     */
    public void display(Activity activity,final View contentView, JsDisplayStyle style, JsDisplayCallback callback) {
        // 1 生成style.
        if(style == null) {
            style = new JsDisplayStyle();

            //默认用110dp.居中显示.
            int size = JsGeometryManager.pixelFromDp(110);
            RelativeLayout.LayoutParams contentViewInitialLayoutParams = new RelativeLayout.LayoutParams(size, size);
            contentViewInitialLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
            style.mRelativeLayoutParams_contentViewInitialLayoutParams = contentViewInitialLayoutParams;
            style.isMaskViewClickable = false;
        }
        //2 获取activity的R.id.content的framelayout.
        final FrameLayout containerView = getContentFrameLayout(activity);

        //3
        final RelativeLayout maskView = generateMaskView(activity,style);
        ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        containerView.addView(maskView, lp);

        JsViewDisplayStyle viewDisplayStyle = new JsViewDisplayStyle();
        viewDisplayStyle.mLayoutParams_subviewInitialLayoutParams = style.mRelativeLayoutParams_contentViewInitialLayoutParams;
        viewDisplayStyle.displayAnimationType = style.displayAnimationType;
        viewDisplayStyle.undisplayAnimationType = style.unDisplayAnimationType;

        JsViewDisplayManager.sharedInstance().display(contentView, maskView, viewDisplayStyle, null);

        //3 添加至map保存信息.
        map_container.put(contentView,containerView);

        //4 保存contentView和callback.
        if(callback != null) {
            map_callback.put(contentView, callback);
        }

        //监听键盘以修正view的位置.
        if(style.mb_isObserveKeybord) {
            addKeyboardObserver(maskView, contentView);
        }

        //隐藏的定时器
        if(style.mI_duration != null) {
            //这种不好,需要可以取消的方式.

            Timer timer = new Timer();
            map_timer.put(contentView,timer);
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                    JsThreadManager.runInMainThreadImmediately(new Runnable() {
                        @Override
                        public void run() {
                            //主线程执行.
                            undisplay(contentView);
                        }
                    });

                }
            };
            timer.schedule(task,style.mI_duration * 1000);
        }
    }


    /**
     * 从Activity.ContentView上移除ContentView,MaskView,以及相关资源.
     * 1,首先将contentView从maskView上移除with animation.
     * @param contentView
     */
    public void undisplay(final View contentView) {
        //Timer处理
        Timer timer_undisplay = map_timer.get(contentView);
        if(timer_undisplay != null) {
            timer_undisplay.cancel();
            map_timer.remove(contentView);
        }
        JsViewDisplayManager.sharedInstance().undisplay(contentView, new JsViewUndisplayCallback() {
            @Override
            public void onUndisplayFinished(View subview) {
                RelativeLayout maskView = (RelativeLayout)contentView.getParent();
                FrameLayout frameLayout = map_container.get(contentView);
                frameLayout.removeView(maskView);
                map_observer.remove(contentView);
                maskView.removeAllViews();
                JsDisplayCallback callback = map_callback.get(contentView);
                if(callback != null) {
                    callback.onUndisplay(contentView);
                    map_callback.remove(contentView);
                }
                //清除style
                map_callback.remove(contentView);
            }
        });



    }


    //添加到Activity的CotentView上,效果就不错了.
    static private FrameLayout getContentFrameLayout(Activity activity) {
        Window window = activity.getWindow();
        ViewGroup vp = (ViewGroup) window.getDecorView();
        FrameLayout frameLayout = vp.findViewById(android.R.id.content);
        return frameLayout;
    }


    // 1 - 2 -1 取消loadingReminder.
    public void undisplayLoadingReminder(Activity activity) {
        int loadingCount = decreaseActivityLoadingCount(activity);
        if (loadingCount == 0) {
            View loadingReminder = getLoadingReminder(activity);
            undisplay(loadingReminder);
            mMap_loadingReminder.remove(activity);
        }
    }

    //1 - 2 -2 彻底取消loadingReminder.
    public void undisplayLoadingReminderForce(Activity activity) {
        if(mMap_loadingCount != null) {
        mMap_loadingCount.remove(activity);
        View loadingReminder = getLoadingReminder(activity);
        undisplay(loadingReminder);
        mMap_loadingReminder.remove(activity);
        }
    }

    // 获取Activity的方法
    public Activity getActivityFromView(View view) {
        if (view == null) {
            return null;
        }
        Context context = view.getContext();
        if (context instanceof Activity) {
            return (Activity) context;
        } else if (context instanceof ContextWrapper) {
//            ContextWrapper contextWrapper = (ContextWrapper) context;
//            View v = (View)contextWrapper.getBaseContext();
//            return getActivityFromView((View)contextWrapper.getBaseContext());
            return null;
        }
        return null;
    }

    /**
     * 首先获取view的Activity然后显示该View.
     * 最终还是添加在FrameLayout上面.
     * @param message
     * @param view
     */
    public void displayMessage(final String message, final View view) {
        Activity activity = getActivityFromView(view);
        if(activity != null) {
            displayMessage(message,activity);
        }
    }


    public void displayMessage(final String message, final Activity activity) {
        JsThreadManager.runInMainThreadImmediately(new Runnable() {
            @Override
            public void run() {
                displayMessage(message, null,activity);
            }
        });
    }

    public void displayMessage(String message, final JsDisplayStyle style , Activity activity) {
        displayMessage(message, null, style,activity);
    }


     public void displayMessage (String message,Activity activity,JsReminderManager.JsMessageReminderType type ) {
        View messageReminder = JsReminderManager.getMessageReminderIl(activity,type,message);

        //默认用110dp.居中显示.
        int size = JsGeometryManager.pixelFromDp(110);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lp.addRule(RelativeLayout.CENTER_IN_PARENT);

        JsDisplayStyle style = new JsDisplayStyle();
        style.mI_duration = 3;
        style.mRelativeLayoutParams_contentViewInitialLayoutParams = lp;

        display(activity,messageReminder,style,null);
    }

    /**
     * 显示一个消息和一个图片. 图片可为空.
     * @param message 要显示的消息
     * @param drawable 要显示的图片
     * @param style 显示的样式
     * @param activity activity.
     */
    public void displayMessage(String message, Drawable drawable, JsDisplayStyle style, Activity activity) {
        View contentView = null;
        if(drawable != null) {
            contentView = JsReminderManager.getMessageReminderIl(drawable, message, activity);

            //如果有图片,尺寸是固定的size.
            if(style == null) {
                //Message的默认样式.
                style = new JsDisplayStyle();
                //默认用110dp.居中显示.
                int size = JsGeometryManager.pixelFromDp(110);
                RelativeLayout.LayoutParams contentViewInitialLayoutParams = new RelativeLayout.LayoutParams(size, size);
                contentViewInitialLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
                style.mRelativeLayoutParams_contentViewInitialLayoutParams = contentViewInitialLayoutParams;
                style.isMaskViewClickable = false;
                style.mI_duration = 3;
            }
        }
        else {
            contentView = JsReminderManager.getMessageRemindL(activity,message);

            //如果没有图片,采用wrap的.
            if(style == null) {
                //Message的默认样式.
                style = new JsDisplayStyle();
                //默认用110dp.居中显示. 用屏幕的一半来显示?
                RelativeLayout.LayoutParams contentViewInitialLayoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                contentViewInitialLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
                style.mRelativeLayoutParams_contentViewInitialLayoutParams = contentViewInitialLayoutParams;
                style.isMaskViewClickable = false;
                style.mI_duration = 3;
            }
        }

        // 1 生成style.


        display(activity,contentView,style,null);
//        //2 获取activity的R.id.content的framelayout.
//        final ContentFrameLayout containerView = getContentFrameLayout(activity);
//
//        //3 生成maskView
//        final RelativeLayout maskView = generateMaskView(activity,style);
//        ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
//        containerView.addView(maskView, lp);
//
//
//        style.mb_isReminderDisplaying = true;
//
//
//        final View finalContentView = contentView;
//        mHandler_main.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                undisplay(finalContentView);
//            }
//        }, 3000);
    }


    public View getLoadingReminderViewStandard1(Context context) {
        FrameLayout container = new FrameLayout(context);
        //TODO: Get real height screen;
        FrameLayout.LayoutParams lp_full = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        lp_full.gravity = Gravity.CENTER;
        container.setLayoutParams(lp_full);


        View maskView = new View(context);
        maskView.setLayoutParams(lp_full);
        maskView.setBackgroundColor(0x77333333);
        container.addView(maskView);
        maskView.setClickable(true);
        maskView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        //一个view的layoutParams用来告诉父视图,如何布局自己
        View contentView = new JsLoadingReminderStandard1(context);
        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(300, 300);
        lp.gravity = Gravity.CENTER;
        contentView.setLayoutParams(lp);
        container.addView(contentView);

        return container;
    }

    /**
     * 获取状态栏高度
     *
     * @param context
     * @return
     */
    public int getStatusBarHeight(Context context) {
        Resources resources = context.getResources();
        int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
        int height = resources.getDimensionPixelSize(resourceId);
        return height;
    }

     public void addKeyboardObserver(final View rootView, final View contentView) {
        ViewTreeObserver.OnGlobalLayoutListener globalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect r1 = new Rect();
                Rect r2 = new Rect();
                //获取当前窗口实际的可见区域

                //1794,没有包含状态栏.
//                    int screenHeight = JsGeometryManager.getDevicePixelSize().getHeight();

                //JsGeometryManager.getDevicePixelSize().getHeight() = 1794.
                //contentView-getWindowVisibleDisplayFrame --> (0,63 - 1080,1794) 表示contentView在window的区域是这个.后面的那个点是有下家的坐标,而不是高度.
                //conentView.getBottom = 1731, getTop = 0,是自身的坐标系.
                //contentView.getGlobalVisibleRect (0,0,1080,1794), 感觉这个是真真的手机全屏的尺寸.

                //decorView-getWindowVisibleDisplayFrame --> (0,63 - 1080,1794)
                //decorView,top:0,bottom:1920. decorView的bottom是1920,怎么这么多???

                rootView.getWindowVisibleDisplayFrame(r1);
                //getDrawingRect getLocalVisibleRect
                //getHitRect getGlobalVisibleRect
                rootView.getGlobalVisibleRect(r2);
//                JsLogManager.logc_d("xx","display frame,top:%d,bottom:%d,height:%d",r.top,r.bottom,r.height());
//                JsLogManager.logc_d("xx","root view,top:%d,bottom:%d,height:%d",rootView.getTop(),rootView.getBottom(),rootView.getHeight());
                int raiseHeight = r2.bottom - r1.bottom;

                JsLogManager.logc_d("JsDisplayManagerGamma", "Raise height is %d", raiseHeight);
                RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) contentView.getLayoutParams();
                lp.setMargins(0, 0, 0, raiseHeight);
                contentView.setLayoutParams(lp);

            }
        };
        rootView.getViewTreeObserver().addOnGlobalLayoutListener(globalLayoutListener);
        map_observer.put(rootView, globalLayoutListener);
    }
}
